package auth

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"tacitus/library/error"
)

// 检查用户是否已经登录
func CheckLogin(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		token := c.Request().Header.Get(echo.HeaderAuthorization)
		if token == "" {
			return errs.Called("用户未登录，请先登录或注册", -1)
		}
		claims := new(Claims)
		if _, err := jwt.ParseWithClaims(token, claims, KeyProvider); err != nil {
			if _err, ok := err.(*jwt.ValidationError); ok {
				if _err.Errors == jwt.ValidationErrorExpired {
					return errs.Called("登陆超时", -1)
				}
			}
			return err
		}
		c.Set("user", claims)
		return next(c)
	}
}

// 检查用户是否登录，并且有访问权限
func CheckAuth(code string) echo.MiddlewareFunc {
	RegisterAccess(code)
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			token := c.Request().Header.Get(echo.HeaderAuthorization)
			if token == "" {
				return errs.Called("用户未登录，请先登录或注册", -1)
			}
			claims := new(Claims)
			if _, err := jwt.ParseWithClaims(token, claims, KeyProvider); err != nil {
				if _err, ok := err.(*jwt.ValidationError); ok {
					if _err.Errors == jwt.ValidationErrorExpired {
						return errs.Called("登陆超时", -1)
					}
				}
				return err
			}
			if !CheckAccess(claims.AccessControlList, code) {
				return errs.Called("您没有此功能的访问权限", -2)
			}
			c.Set("user", claims)
			return next(c)
		}
	}
}

func CurrentUser(c echo.Context) *Claims {
	claims, ok := c.Get("user").(*Claims)
	if !ok {
		panic(errs.Called("用户未登录，请先登录或注册", -1))
	}
	return claims
}